# @time     :2022/2/22
# @Author   :Simple
# @FileName :read_yaml_case
from typing import List

import yaml
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

from util.logger import log as logger
from util.handle_black_list import handle_black


# 读取yaml格式的测试用例
class ReadYamlCase:
    def __init__(self, driver: WebDriver):
        self.driver = driver
        self.driver.implicitly_wait(5)

    def parse(self, yaml_path, fun_name):
        """
        读取yaml文件中的步骤，进行转换，实现关键字驱动
        :param yaml_path: 测试用例yaml文件路径（包含文件名）
        :param fun_name: yaml文件中的函数名
        :return:
        例如: parse("main_page.yml", "goto_market")
        """
        with open(yaml_path, "r", encoding='utf-8') as file:
            function = yaml.safe_load(file)
            logger.debug(function)
        steps = function.get(fun_name)
        for step in steps:
            if step.get("action") == "wait_find_click":
                self.wait_find(step.get("locator"), step.get("value")).click()
            elif step.get("action") == "wait_find":
                self.wait_find(step.get("locator"), step.get("value"))
            elif step.get("action") == "find_and_click":
                self.find_and_click(step.get("locator"), step.get("value"))
            elif step.get("action") == "find_and_sendkeys":
                self.find_and_sendkeys(step.get("locator"), step.get("value"), step.get("content"))

    @handle_black
    def find(self, locator, value) -> WebElement:
        return self.driver.find_element(locator, value)

    @handle_black
    def finds(self, locator, value) -> List[WebElement]:
        return self.driver.find_elements(locator, value)

    def find_and_click(self, locator, value):
        self.find(locator, value).click()

    def find_and_sendkeys(self, locator, value, content):
        ele = self.find(locator, value)
        ele.clear()
        ele.send_keys(content)

    @handle_black
    def find_children(self, ele: WebElement, locator, value) -> List[WebElement]:
        return ele.find_elements(locator, value)

    @handle_black
    def find_child(self, ele: WebElement, locator, value) -> WebElement:
        return ele.find_element(locator, value)

    @handle_black
    def wait_find(self, locator, value) -> WebElement:
        """
        等待节点出现并且查找到
        :param locator:
        :param value:
        :return: WebElement
        """
        return WebDriverWait(self.driver, 10).until(
            expected_conditions.visibility_of_element_located((locator, value)))

    def screenshot(self):
        self.driver.get_screenshot_as_png()
